package com.zulu.watchall.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerPNames;
import org.apache.http.conn.params.ConnPerRouteBean;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.SingleClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import com.zulu.watchall.R;
import com.zulu.watchall.certificate.FTEasySSLSocketFactory;
import com.zulu.watchall.constant.Constants;
import com.zulu.watchall.system.UserSetting;
import com.zulu.watchall.ui.widget.CustomProgressDialog;

public class ConnectionUtils {

	/**
	 * 
	 * @param context
	 */
	public static void registerCheckStateInternetConnection(Context context) {
		String ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
		IntentFilter filter = new IntentFilter(ACTION);
		context.registerReceiver(mConnectivityCheckReceiver, filter);
	}

	/**
	 * @param context
	 */
	public static void unregisterCheckStateInternetConnection(Context context) {
		context.unregisterReceiver(mConnectivityCheckReceiver);
	}

	/**
	 * mConnectivityCheckReceiver
	 */
	private static BroadcastReceiver mConnectivityCheckReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {

			boolean isNoConnectivity = intent.getBooleanExtra(
					ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);

			if (isNoConnectivity) {
				UserSetting.getInstance().isConnectInternet = false;
			} else {
				UserSetting.getInstance().isConnectInternet = true;
				if (UserSetting.getInstance().isLoggedIn()) {
					// Do...
				}
			}
		}
	};

	/**
	 * 
	 * @param context
	 */
	public static void checkConnectInternet(Context context) {
		ConnectivityManager conManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo i = conManager.getActiveNetworkInfo();
		if ((i == null) || (!i.isConnected()) || (!i.isAvailable())) {
			UserSetting.getInstance().isConnectInternet = false;
		} else {
			UserSetting.getInstance().isConnectInternet = true;
		}
	}

	/**
	 * 
	 * @param url
	 * @return
	 */
	public static String executeHttpGet(String url) {
		BufferedReader in = null;
		String result = "";
		try {
			HttpClient client = createHttpClient();
			// HttpClient client = new DefaultHttpClient();
			// Timeout Limit
			HttpParams params = client.getParams();
			HttpConnectionParams.setConnectionTimeout(params,
					Constants.ConnectionUtils.TIMEOUT_LIMIT);
			HttpConnectionParams.setSoTimeout(params,
					Constants.ConnectionUtils.TIMEOUT_LIMIT);

			HttpGet request = new HttpGet();
			request.setURI(new URI(url.replace(" ", "%20")));
			HttpResponse response = client.execute(request);
			in = new BufferedReader(new InputStreamReader(response.getEntity()
					.getContent()));
			StringBuffer sb = new StringBuffer("");
			String line = "";
			while ((line = in.readLine()) != null) {
				sb.append(line);
			}
			in.close();
			result = sb.toString();
		} catch (Exception e) {
			e.printStackTrace();
		} catch (OutOfMemoryError e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return result;
	}

	/**
	 * 
	 * @return
	 */
	private static HttpClient createHttpClient() {
		SchemeRegistry schemeRegistry = new SchemeRegistry();
		schemeRegistry.register(new Scheme("http", PlainSocketFactory
				.getSocketFactory(), 80));
		schemeRegistry.register(new Scheme("https",
				new FTEasySSLSocketFactory(), 443));

		HttpParams params = new BasicHttpParams();
		params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30);
		params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE,
				new ConnPerRouteBean(30));
		params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false);
		HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);

		ClientConnectionManager cm = new SingleClientConnManager(params,
				schemeRegistry);
		return new DefaultHttpClient(cm, params);

	}

	/**
	 * 
	 * @param url
	 * @param content
	 * @return
	 */
	public static String executeHttpPost(String url, String content) {
		HttpClient client = createHttpClient(); // new DefaultHttpClient();
		HttpConnectionParams.setConnectionTimeout(client.getParams(),
				Constants.ConnectionUtils.TIMEOUT_LIMIT); // Timeout Limit
		HttpResponse response;
		String result = "";
		try {
			StringEntity se = new StringEntity(content);
			// se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
			// "application/json"));
			HttpPost post = new HttpPost(url);
			post.setEntity(se);
			post.setHeader("Content-type", "application/x-www-form-urlencoded");
			response = client.execute(post);
			/* Checking response */
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				result = EntityUtils.toString(response.getEntity()); // Get the
																		// data
																		// in
																		// the
																		// entity
			}
		} catch (Exception e) {
			e.printStackTrace();
		} catch (OutOfMemoryError e) {
			e.printStackTrace();
		}
		return result;
	}

	public static String executeHttpPost(String url, List<NameValuePair> content) {
		HttpClient client = createHttpClient(); // new DefaultHttpClient();
		HttpConnectionParams.setConnectionTimeout(client.getParams(),
				Constants.ConnectionUtils.TIMEOUT_LIMIT); // Timeout Limit
		HttpResponse response;
		String result = "";
		try {
			// se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
			// "application/json"));
			HttpPost post = new HttpPost(url);
			post.setEntity(new UrlEncodedFormEntity(content, HTTP.UTF_8));
//			post.setHeader("Accept-Encoding", "gzip,deflate,sdch");
//			post.setHeader("Accept-Language", "vi,en-US;q=0.8,en;q=0.6");
			post.setHeader("Content-type", "application/x-www-form-urlencoded;charset=utf8");
			response = client.execute(post);
			result = EntityUtils.toString(response.getEntity());
			/* Checking response */
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				result = EntityUtils.toString(response.getEntity()); // Get the
																		// data
																		// in
																		// the
																		// entity
			}
		} catch (Exception e) {
			e.printStackTrace();
		} catch (OutOfMemoryError e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 
	 */
	public static class ExcuteHttpPostThread extends
			AsyncTask<Void, Void, String> {
		private String url;
		private String content;
		private List<NameValuePair> params;
		private int index = -1;
		private long categoryId = -1;
		private CustomProgressDialog progressDialog;
		private Context context;
		private Handler handler;
		private boolean isHideDialog = false;

		public ExcuteHttpPostThread(Context context, Handler handler,
				String url, String content) {
			this.url = url;
			this.content = content;
			this.context = context;
			this.handler = handler;
		}

		public ExcuteHttpPostThread(Context context, Handler handler,
				String url, List<NameValuePair> params) {
			this.url = url;
			this.params = params;
			this.context = context;
			this.handler = handler;
		}

		public ExcuteHttpPostThread(Context context, Handler handler,
				String url, String content, boolean isHideDialog) {
			this.url = url;
			this.content = content;
			this.context = context;
			this.handler = handler;
			this.isHideDialog = isHideDialog;
		}

		public ExcuteHttpPostThread(Context context, Handler handler,
				String url, String content, int index, long categoryId,
				boolean isHideDialog) {
			this.url = url;
			this.content = content;
			this.context = context;
			this.handler = handler;
			this.index = index;
			this.categoryId = categoryId;
			this.isHideDialog = isHideDialog;
		}

		@Override
		protected void onPreExecute() {
			if (!isHideDialog) {
				progressDialog = new CustomProgressDialog(context,
						context.getString(R.string.connecting));
			}
			super.onPreExecute();
		}

		@Override
		protected void onPostExecute(String result) {
			if (!isHideDialog) {
				progressDialog.hideDialog();
			}

			if (result.equals("")) {
				handler.sendEmptyMessage(Constants.APIConstant.HANDLER_REQUEST_FAIL);
			} else {
				Message msg = Message.obtain();
				msg.what = Constants.APIConstant.HANDLER_REQUEST_SUCCESS;
				msg.obj = result;

				if (index != -1) {
					msg.arg2 = (int) categoryId;
					msg.arg1 = index;
				}

				handler.sendMessage(msg);
			}
			super.onPostExecute(result);
		}

		@Override
		protected String doInBackground(Void... param) {
			if (params != null) {
				return ConnectionUtils.executeHttpPost(url, params);
			}
			return ConnectionUtils.executeHttpPost(url, content);

		}
	}

	/**
	 *
	 */
	public static class ExcuteHttpSubmitThread extends
			AsyncTask<Void, Void, String> {
		private String url;
		private String content;
		private Handler handler;
		private long taskItemId;

		public ExcuteHttpSubmitThread(Context context, Handler handler,
				String url, String content, long taskItemId) {
			this.url = url;
			this.content = content;
			this.handler = handler;
			this.taskItemId = taskItemId;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected void onPostExecute(String result) {
			if (handler != null) {
				if (result.equals("")) {
					handler.sendEmptyMessage(Constants.APIConstant.HANDLER_REQUEST_FAIL);
				} else {
					Message msg = Message.obtain();
					msg.what = Constants.APIConstant.HANDLER_REQUEST_SUCCESS;
					Bundle bundle = new Bundle();
					bundle.putLong("ID", taskItemId);
					bundle.putString("RESULT", result);
					msg.obj = bundle;
					handler.sendMessage(msg);
				}
			}
			super.onPostExecute(result);
		}

		@Override
		protected String doInBackground(Void... params) {
			return ConnectionUtils.executeHttpPost(url, content);
		}

	}

	/**
	 *
	 */
	public static class ExcuteHttpGetThread extends
			AsyncTask<Void, Void, String> {
		private String url;
		private CustomProgressDialog progressDialog;
		private Context context;
		private Handler handler;
		private boolean isHideProgressDialog;

		public ExcuteHttpGetThread(Context context, Handler handler,
				String url, boolean isHideProgressDialog) {
			this.url = url;
			this.context = context;
			this.handler = handler;
			this.isHideProgressDialog = isHideProgressDialog;
		}

		@Override
		protected void onPreExecute() {
			if (!isHideProgressDialog) {
				progressDialog = new CustomProgressDialog(context,
						context.getString(R.string.connecting));
			}
			super.onPreExecute();
		}

		@Override
		protected void onPostExecute(String result) {
			if (!isHideProgressDialog) {
				progressDialog.hideDialog();
			}

			if (result.equals("")) {
				handler.sendEmptyMessage(Constants.APIConstant.HANDLER_REQUEST_FAIL);
			} else {
				Message msg = Message.obtain();
				msg.what = Constants.APIConstant.HANDLER_REQUEST_SUCCESS;
				msg.obj = result;
				handler.sendMessage(msg);
			}
			super.onPostExecute(result);
		}

		@Override
		protected String doInBackground(Void... params) {
			return ConnectionUtils.executeHttpGet(url);
		}

	}

	/**
	 *
	 */
	public static class ExcuteDownloadFile extends
			AsyncTask<Void, Void, Boolean> {
		private String url;
		private String pathFile;
		private CustomProgressDialog progressDialog;
		private Context context;
		private Handler handler;

		public ExcuteDownloadFile(Context context, Handler handler, String url,
				String pathFile) {
			this.url = url;
			this.pathFile = pathFile;
			this.context = context;
			this.handler = handler;
		}

		@Override
		protected void onPreExecute() {
			progressDialog = new CustomProgressDialog(context,
					context.getString(R.string.connecting));
			super.onPreExecute();
		}

		@Override
		protected void onPostExecute(Boolean result) {
			progressDialog.hideDialog();

			if (result) {
				handler.sendEmptyMessage(Constants.APIConstant.HANDLER_REQUEST_SUCCESS);
			} else {
				handler.sendEmptyMessage(Constants.APIConstant.HANDLER_REQUEST_FAIL);
			}
			super.onPostExecute(result);
		}

		@Override
		protected Boolean doInBackground(Void... params) {
			return GeneralUtils.downloadFile(url, pathFile);
		}
	}
}
